package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;


@Service
public class UserInfoService {

    static final String prefixPh = "CHECK_CODE";//手机前缀
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1.将图片上传到阿里云oss
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.将图片上传到百度人脸识别
//        boolean detect = aipFaceTemplate.detect(imgUrl);
        //2.1不包含人脸,抛出异常
//        if (!detect){
//            throw new BusinessException(ErrorResult.faceError());
//        }else {
            //2.2包含人脸,调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(imgUrl);
            userInfoApi.update(userInfo);
//        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 修改手机号- 1 发送短信验证码
     */
    public void sendVerificationCode() {
        //1.获取用户手机
        String mobile = UserHolder.getMobile();
        //2.随机生成验证码
        String code = "123456";
        //3.将验证码存入Redis设置5分钟失效
        redisTemplate.opsForValue().set(prefixPh+mobile,code,Duration.ofMinutes(5));
        System.out.println("验证码存入成功");
    }

    /**
     * 修改手机号 - 2 校验验证码
     */
    public boolean checkVerificationCode(String code) {
        System.out.println("进入校验");
        System.out.println(code);
        boolean isNew = true;
        //1.在redis中获取验证码
        String mobile = UserHolder.getMobile();
        String redisCode = redisTemplate.opsForValue().get(prefixPh + mobile);
        System.out.println(redisCode);
        //2.对比验证码
        if (!redisCode.equals(code)) {
            //验证码无效
            isNew =false;
        }
        //3.删除验证码
        redisTemplate.delete(prefixPh+mobile);
        System.out.println(isNew);
        return isNew;
    }

    /**
     * 保存新手机
     * @param
     */
    public void updatePhone(Map map) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.根据用户id返回用户
        User user = userApi.findById(userId);
        //3.修改手机号
        String phone = (String) map.get("phone");
        user.setMobile(phone);
        userApi.update(user);
    }
    //判断是否喜欢
    public Boolean islike(Long userId, Long likeUserId){
        String key = Constants.USER_LIKE_KEY+userId;
        return redisTemplate.opsForSet().isMember(key,likeUserId.toString());
    }
    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     */
    public CountsVo counts(Long userId) {
        //1.查找你喜欢的
        List<UserLike> userLikes = userLikeApi.findByIdUserLikes(userId,true);
        Integer loveCount = userLikes.size();
        //
//        String key = Constants.USER_LIKE_KEY+userId;
//        Set<String> members = redisTemplate.opsForSet().members(Constants.USER_LIKE_KEY + userId);
//        Integer loveCount = members.size();
        //2.是否是互相喜欢
        Integer eachLoveCount = 0;
        List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        System.out.println(likeUserIds);
        for (Long likeUserId : likeUserIds) {
            if (islike(likeUserId,userId)) {
                eachLoveCount += 1;
            }
        }
        //3.查找粉丝
        List<UserLike> fsCount = userLikeApi.findByIdfsLikes(userId,true);
        Integer fanCount = fsCount.size();
        CountsVo countsVo = new CountsVo();
        countsVo.setEachLoveCount(eachLoveCount);
        countsVo.setFanCout(fanCount);
        countsVo.setLoveCout(loveCount);
        System.out.println(countsVo);
        //(eachLoveCount=1, loveCout=5, fanCout=1)
        return countsVo;
    }
}
